import axios from 'axios'
import service from './contact'
import {Toast } from 'vant';

let instance = axios.create({
    baseURL:' http://localhost:9000/api',//基本地址
    timeout:1000
    })
const Http={ };
//请求格式统一
for( let key  in service){
    let  api = service[key]//url method
    //async 避免回调地狱   配合 await
    Http[key] = async function (
        params,//请求参数
        isFormData =false,//是否FormData请求
        config={} //配置参数
    ){
        let newParams = {}
        if(params && isFormData){
            newParams = new FormData
            for (let key in params) {
                newParams.append(key,params[key])
            }
        }else{
            newParams = params
        }
        //不同请求的判断
        let response ={};//请求返回值
        if(api.method == 'put' || api.method == 'post' || api.method == 'patch' ){
            try{
                response = await instance[api.method](api.url,newParams,config)
            }catch(err){
                response = err
            }
        }else{
            //get delete
            config.params = newParams
            try{
                response = await instance[api.method](api.url,config)
            }catch(err){
                response = err
            }
        }

        return response
   
    }
}

//拦截器的添加
instance.interceptors.request.use(config=>{
    //发起请求前
    Toast.loading({
        mask:false,//阴影
        duration:0,//一直存在
        forbidClick:true,//禁止点击
        message:'加载中...'
    })
    return config
},()=>{
    //请求错误
    Toast.clear()
    Toast('请求错误，请稍后尝试')
})



//响应拦截器
instance.interceptors.response.use(res=>{
    Toast.clear()
    return res.data
},()=>{
    //请求错误
    Toast.clear()
    Toast('请求错误，请稍后尝试')
})

export default Http